<template>
	<view class="drop-btn" :class="{active:!(activeList.length==0&&activeItem=='')}" @click.stop="toggleShow">
		<slot :activeList="activeList"></slot>
		<view class="drop-box" v-if="active">
			<view class="drop-btn" @click.stop="chooseItem()" :class="{active:activeList.length==0&&activeItem==''}"
				v-if="multiple">
				全部
			</view>
			<view class="drop-btn drop" :class="{active:activeList.includes(item.id)||activeItem==item.id}"
				v-for="(item,index) of list" :key="item.id" @click.stop="chooseItem(item.id,index)">
				{{item.name}}
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "hs-drop-down",
		props: {
			list: {
				type: Array,
				default: () => []
			},
			multiple: {
				type: Boolean,
				default: false
			},
			defaultActive: {
				type: Array,
				default: () => []
			},
		},
		data() {
			return {
				active: false,
				activeList: [],
				activeItem: '',
			};
		},
		watch: {
			defaultActive(newValue, oldValue) {
				if (newValue.length != 0) {
					if (this.multiple) {
						this.activeList = newValue
					} else {
						this.activeItem = newValue[0]
					}
				}
			},
			list(newValue, oldValue) {
				if (!this.multiple) {
					let index = newValue.findIndex(item => {
						return item.id == this.defaultActive[0]
					})
					this.chooseItem(this.defaultActive[0], index, true)
				}
			},
		},
		methods: {
			chooseItem(id, index, init) {
				if (!id) {
					this.multiple ? this.activeList = [] : this.activeItem = ''
					this.$emit('chooseMenu', this.multiple ? this.activeList : this.activeItem)
					return
				}
				if (this.multiple) {
					this.activeList.includes(id) ?
						this.activeList.splice(this.activeList.indexOf(id), 1) :
						this.activeList.push(id)
					this.$emit('chooseMenu', this.activeList)
				} else {
					this.activeItem = id
					this.$emit('chooseMenu', {
						id: this.activeItem,
						index,
						init
					})
				}
			},
			toggleShow() {
				this.active = !this.active
				this.$emit('menuActive', this.active)
			}
		}
	}
</script>

<style lang="scss">
	.drop-btn {
		height: 43.7rpx;
		min-width: 148rpx;
		line-height: 43.7rpx;
		text-align: center;
		border-radius: 21.8rpx;
		color: #3c4242;
		background: #ffffff;
		font-size: 22rpx;
		font-weight: 500;
		margin-right: 16rpx;
		position: relative;
		white-space: nowrap;
		padding: 0 17rpx;

		&.active {
			background: #333333;
			color: #fff;
		}

		.drop-box {
			background-color: #EAEAEA75;
			position: absolute;
			padding: 17rpx 17rpx 0;
			z-index: 9;
			border-radius: 17rpx;
			left: 50%;
			transform: translateX(-50%);

			.drop-btn {
				margin-bottom: 17rpx;
				margin-right: 0;
			}
		}
	}
</style>